package gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

import model.Location;
import service.Service;

public class EditLocation extends JFrame {
    static {
	try {
	    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	} catch (Exception e) {
	    System.out.println("Error setting look & feel: " + e.getMessage());
	}
    }

    private final Controller controller = new Controller();
    private JButton btnEdit, btnCancel;
    private JCheckBox chckbxActive;
    private StackPanel owner;
    private JPanel panel_1;
    private JLabel lblToChangeThis;

    public EditLocation(StackPanel owner) {
	this.owner = owner;

	this.setSize(300, 120);

	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	setVisible(true);
	setTitle("Edit Location");
	getContentPane().setLayout(new GridLayout(3, 0, 0, 0));

	panel_1 = new JPanel();
	FlowLayout flowLayout_1 = (FlowLayout) panel_1.getLayout();
	flowLayout_1.setAlignment(FlowLayout.LEFT);
	getContentPane().add(panel_1);

	lblToChangeThis = new JLabel("To change this, location should be empty");
	panel_1.add(lblToChangeThis);
	lblToChangeThis.setVisible(false);

	JPanel panel = new JPanel();
	FlowLayout flowLayout = (FlowLayout) panel.getLayout();
	flowLayout.setAlignment(FlowLayout.LEFT);
	getContentPane().add(panel);

	chckbxActive = new JCheckBox("Location is active");
	panel.add(chckbxActive);
	chckbxActive.setSelected(owner.getStackLocation().isActive());

	JPanel panel_2 = new JPanel();
	FlowLayout flowLayout_2 = (FlowLayout) panel_2.getLayout();
	flowLayout_2.setVgap(2);
	flowLayout_2.setAlignment(FlowLayout.RIGHT);
	getContentPane().add(panel_2);

	btnEdit = new JButton("Edit");
	panel_2.add(btnEdit);
	btnEdit.addActionListener(controller);

	btnCancel = new JButton("Cancel");
	panel_2.add(btnCancel);
	btnCancel.addActionListener(controller);

	if (owner.getStackLocation().getStack() != null) {
	    chckbxActive.setEnabled(false);
	    lblToChangeThis.setVisible(true);
	    btnEdit.setEnabled(false);
	}

    }

    private class Controller implements ActionListener {
	@Override
	public void actionPerformed(ActionEvent e) {
	    if (e.getSource() == btnCancel) {
		EditLocation.this.dispose();
	    } else if (e.getSource() == btnEdit) {
		Location l = Service.getInstance().editLocation(
			owner.getStackLocation(), chckbxActive.isSelected());

		if (l != null) {
		    owner.updateView();
		    EditLocation.this.dispose();
		} else {
		    JOptionPane.showMessageDialog(EditLocation.this,
			    "Location could not be edited", "Error",
			    JOptionPane.ERROR_MESSAGE);
		}
	    }

	}

    }
}